package com.lupengning.payment.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.lupengning.payment.entity.PaymentInfo;
import com.lupengning.payment.enums.PayType;
import com.lupengning.payment.mapper.PaymentInfoMapper;
import com.lupengning.payment.service.PaymentInfoService;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

  @Resource
  private PaymentInfoMapper paymentInfoMapper;

  /**
   *
   * @param plainText
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void createPaymentInfo(String plainText) {

    log.info("记录支付日志");
    Gson gson = new Gson();
    HashMap plainTextMap = gson.fromJson(plainText, HashMap.class);

    String orderNo = (String) plainTextMap.get("out_trade_no");
    String transactionId = (String) plainTextMap.get("transaction_id");
    String tradeType = (String) plainTextMap.get("trade_type");
    String tradeState = (String) plainTextMap.get("trade_state");
    Map<String, Object> amount = (Map) plainTextMap.get("amount");
    Integer payerTotal = ((Double) amount.get("payer_total")).intValue();

    PaymentInfo paymentInfo = PaymentInfo.builder().orderNo(orderNo)
        .paymentType(PayType.WXPAY.getType())
        .transactionId(transactionId)
        .tradeType(tradeType)
        .tradeState(tradeState)
        .payerTotal(payerTotal)
        .content(plainText)
        .build();

    paymentInfoMapper.insert(paymentInfo);
  }
}
